/**
 * Project Name:dyrj-admin
 * File Name:UserServiceImpl.java
 * Package Name:com.dyrj.base.system.user.service.impl
 * Date:2018年1月13日下午2:30:23
 * Copyright (c) 2018, zhang.xiangyu@foxmail.com All Rights Reserved.
*/
package com.dyrj.base.system.user.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.dyrj.base.system.org.dao.TDepartmentMapper;
import com.dyrj.base.system.org.model.TDepartment;
import com.dyrj.base.system.user.params.SysUserParams;
import com.dyrj.base.system.utils.SystemUtil;
import com.dyrj.constant.SysFrameConst;
import com.dyrj.utils.UUIDUtil;
import com.dyrj.vo.PageResultMsg;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dyrj.base.system.role.dao.SysRoleMapper;
import com.dyrj.base.system.role.dao.SysUserRoleLinksMapper;
import com.dyrj.base.system.role.model.SysRole;
import com.dyrj.base.system.user.dao.SysUserMapper;
import com.dyrj.base.system.user.model.SysUser;
import com.dyrj.base.system.user.service.SysUserService;
import com.dyrj.utils.MD5Util;
import com.dyrj.vo.ResultMsg;

/**   
 * @Title: UserServiceImpl.java 
 * @Package com.dyrj.base.system.user.service.impl
 * @Description: TODO(用户管理) 
 * @author
 * @date 2018年1月13日 下午2:30:23 
 * @version V1.0   
 */
@Service
public class SysUserServiceImpl implements SysUserService {
	@Resource
	private SysUserMapper mapper;
	@Resource
	private SysRoleMapper roleMapper;
	@Resource
	private SysUserRoleLinksMapper linksMapper;
	@Resource
	private TDepartmentMapper tDepartmentMapper;

	@Override
	public PageResultMsg table(SysUser record) {
		SysUser loginUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setLoginUser(loginUser.getAccount());
		PageInfo<SysUser> list = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> mapper.selectList(record));
		return new PageResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, list.getTotal(), list.getList());
	}

	@Override
	public PageResultMsg selectuser_table(SysUser record) {
		SysUser loginUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		record.setLoginUser(loginUser.getAccount());
		PageInfo<SysUser> list = PageHelper.startPage(record.getOffset(), record.getLimit()).doSelectPageInfo(() -> mapper.selectUserList(record));
		return new PageResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, list.getTotal(), list.getList());
	}

	@Override
	public ResultMsg add(SysUser record, Long[] roles) {
		int status  = mapper.selectByAccount(record.getAccount());
		if(status > SysFrameConst.ZERO) {
			return new ResultMsg(SysFrameConst.ResultCode.ACCOUNT_EXIST.CODE, SysFrameConst.ResultCode.ACCOUNT_EXIST.MESSAGE);
		} else {
			String salt = MD5Util.getRandomString(SysFrameConst.SALT_LEGTH);
			record.setPassword(MD5Util.md5(record.getPassword(), salt));
			record.setSalt(salt);
			record.setStatus(SysFrameConst.ONE);
			record.setCreatetime(new Date());
			record.setAppid(SystemUtil.createAppid(salt));
			Subject subject = SecurityUtils.getSubject();
			// 保存用户信息进session
			SysUser sysUser = (SysUser)subject.getSession().getAttribute(SysFrameConst.SYSTEM_USER);
			record.setTenantid(sysUser.getTenantid());
			record.setCreatoraccountid(sysUser.getId());
			// 设置调用密码
			record.setAppsecret(MD5Util.md5(UUIDUtil.uuid(), salt));
			mapper.insertSelective(record);
			// 保存与角色关联信息
			if(roles[SysFrameConst.ZERO] != -SysFrameConst.NEGATIVE_ONE) {
				linksMapper.insertUserRoleLinks(record.getId(), roles);
			}
			return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
		}
		
	}
	
	@Override
	public SysUser info(Long id) {
		SysUser sysUser = mapper.selectByPrimaryKey(id);
		List<SysRole> roles = roleMapper.selectRoleByUserId(id);
		sysUser.setRolesVo(roles);
//		SysUser sysUserp = (SysUser)SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		Long tenantid = sysUser.getTenantid();
		if(tenantid!=null) {
			List<TDepartment> tDepartments = tDepartmentMapper.selectAllTreeDept(tenantid);
			List<TDepartment> menus = this.checkedMenus(tDepartments, sysUser.getDeptid());
			sysUser.setDeptVo(menus);
			if (sysUser.getDeptid() != null) {
				TDepartment tDepartment = tDepartmentMapper.selectAllDeptById(sysUser.getDeptid());
				if (tDepartment != null) {
					sysUser.setDeptText(tDepartment.getName());
				}
			}
		}
//		List<TTenant> tTenants = tTenantMapper.selectTenantById(sysUser.getTenantid());
		return sysUser;
	}
	
	@Override
	public ResultMsg update(SysUser record, Long[] roles) {
		String msg = "";
		if(record.isResetPwd()) {
			String salt = MD5Util.getRandomString(SysFrameConst.SALT_LEGTH);
			record.setPassword(MD5Util.md5(SysFrameConst.DEFAULT_PASSWORD, salt));
			record.setSalt(salt);
			SysUser sysUser = (SysUser)SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
			record.setTenantid(sysUser.getTenantid());
			record.setCreatoraccountid(sysUser.getId());
			msg += SysFrameConst.DEFAULT_PASSWORD_MESSAGE;
		}
		mapper.updateByPrimaryKeySelective(record);
		// 删除角色关联信息
		linksMapper.deleteUserRoleLinksByUserId(record.getId());
		// 新增关联信息
		if(roles[SysFrameConst.ZERO] != SysFrameConst.NEGATIVE_ONE) {
			linksMapper.insertUserRoleLinks(record.getId(), roles);
		}
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE + msg);
	}
	
	@Override
	public ResultMsg delete(Long id) {
		mapper.deleteByPrimaryKey(id);
		// 删除角色关联信息
		linksMapper.deleteUserRoleLinksByUserId(id);
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, SysFrameConst.ResultCode.SUCCESS.MESSAGE);
	}

	@Override
	public ResultMsg changePassword(SysUserParams record) {
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(SysFrameConst.SYSTEM_USER);
		// 转换密码为MD5
		String oldPsd = MD5Util.md5(record.getOldPsd(), sysUser.getSalt());
		// 对比原始密码是否相等
		if(sysUser.getPassword().equals(oldPsd)) {
			String salt = MD5Util.getRandomString(SysFrameConst.SALT_LEGTH);
			sysUser.setSalt(salt);
			sysUser.setPassword(MD5Util.md5(record.getNewPsd(), salt));
			mapper.updateByPrimaryKeySelective(sysUser);
		} else {
			return new  ResultMsg(SysFrameConst.ResultCode.ORIGINAL_PASSWORD_ERROR.CODE,
					SysFrameConst.ResultCode.ORIGINAL_PASSWORD_ERROR.MESSAGE);
		}
		return new ResultMsg(SysFrameConst.ResultCode.PASSWORD_CHANGED_SUCCESSFULLY.CODE,
				SysFrameConst.ResultCode.PASSWORD_CHANGED_SUCCESSFULLY.MESSAGE);
	}

	@Override
	public List<SysUser> selectAllTreeUser(Long id) {
		return mapper.selectAllTreeUser(id);
	}
	@Override
	public List<SysUser> selectList() {
		return mapper.selectList(null);
	}
	/**
	 * @Title: deleteNullChildren
	 * @Description: TODO(递归清除空children)
	 * @param menus
	 * @return List<SysMenu>    返回类型
	 */
	private List<TDepartment> checkedMenus(List<TDepartment> menus, Long perms) {
		for(TDepartment info : menus) {
			if(perms==info.getId()) {
				info.setChecked(true);
			}
			if(info.getChildren().isEmpty()) {
				info.setChildren(null);
			} else {
				this.checkedMenus(info.getChildren(), perms);
			}
		}
		return menus;
	}
	@Override
	public ResultMsg selectUserByDeptId(Long id) {
		List list =  mapper.selectUserByDeptId(id);
		return new ResultMsg(SysFrameConst.ResultCode.SUCCESS.CODE, list );
	}
}
